<template>
  <div
    v-if="visible"
    class="config-container"
    :style="containerStyle()"
    @click.stop
  >
    <div class="header">
      <div class="chart-title">{{ currentGridItem.attrName }}</div>

      <div class="func-icon" @click="closeChartConfig">
        <a-icon-font type="iconicon-beifen1" />
      </div>
    </div>

    <div class="config-body">
      <form-render
        v-if="Object.keys(formData).length > 0"
        from="panel"
        :chart-type="chartType"
        :widget-type="currentGridItem.config.widgetType"
        :form-data="formData"
        :widget-info="currentGridItem.dataQuery.data"
        :panel-list="formItems"
        :project-id="projectId"
        :interact-active="currentInterActive"
        class="form-render"
        @change="onFormSettingChange"
        @reset="onFormSettingReset"
      />
    </div>
  </div>
</template>

<script lang="ts">
/* eslint-disable no-unreachable */
import { dataBindKeys } from '@/config/setting-data-bind'
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import KGraphStore from '@/store/modules/k-graph'
import {
  parseSettingToChartOption,
  parseChartType,
} from '@/components/common/VisualizationDashboard/util'
import ChartProtoConfig from '@/components/common/VisualizationComp/proto-config'
import { cloneDeep, isArray, isEqual } from 'lodash'
import { GEOMAP_NAME, GRAPH_ARRAY } from '@/config/contant'
import FormRender from '@/components/common/VisualizationDashboard/FormRender.vue'

@Component({
  components: {
    FormRender,
  },
})
export default class KChartConfig extends Vue {
  @Prop({ type: Boolean, default: false }) visible!: boolean

  /**
   * 绑定数据
   */
  formData: any = {}

  // 控制加载状态
  loadingCount: number = 0

  /**
   * 配置项
   */
  public formItems: Array<any> = []

  public containerStyle() {
    let { right } = this.currentGridItem
    if (typeof right === 'string' || right instanceof String) {
      right = `${Number(right.slice(0, right.indexOf('px'))) + 300 + 16}px`
    } else {
      //  number case
      right = `${right + 300 + 16}px`
    }

    return {
      right,
    }
  }

  public get currentGridItem() {
    return KGraphStore.currentGridItem
  }

  public get currentInterActive() {
    return this.currentGridItem?.interactActive ?? undefined
  }

  @Watch('currentGridItem', { immediate: true, deep: true })
  getCurrentGridItemId(newValue: any, oldValue: any): void {
    this.checkStatus(newValue)
    if (
      (newValue && !oldValue) ||
      (newValue &&
        oldValue &&
        (newValue.i !== oldValue.i ||
          newValue.chartType[1] !== oldValue.chartType[1]))
    ) {
      this.formData = {}
      setTimeout(() => {
        this.loadingCount += 1
        this.initSetting()
        this.checkStatus(newValue)
      }, 10)
    } else if (
      newValue &&
      oldValue &&
      !isEqual(newValue.chartOptions, oldValue.chartOptions)
    ) {
      this.initFormData()
    }
  }

  checkStatus(newValue: any) {
    if (
      this.currentGridItem &&
      isArray(this.currentGridItem.chartType) &&
      this.currentGridItem.chartType[1] === GEOMAP_NAME
    ) {
      this.setChartOptionStatus(!!(newValue && newValue.chartOptions.value))
      return
    }
    if (
      newValue &&
      newValue.chartOptions.value &&
      newValue.chartOptions.value.length > 0
    ) {
      this.setChartOptionStatus(true)
    } else {
      this.setChartOptionStatus(false)
    }
  }

  setChartOptionStatus(enabled: boolean) {
    this.formItems.forEach((item) => {
      if (item.type !== 'label' && !dataBindKeys.includes(item.name)) {
        item.props = item.props || {}
        this.$set(item.props, 'disabled', !enabled)
      } else if (item.type === 'label' && item.labelbutton) {
        item.props[0].props = item.props[0].props || {}
        this.$set(item.props[0].props, 'disabled', !enabled)
      }
      // geoMap组件暂不支持glyph切换
      if (item.name === 'glyph') {
        this.$set(item.props, 'disabled', true)
      }
    })
  }

  public closeChartConfig() {
    KGraphStore.setCurrentGridItem(null)
  }

  public get projectId() {
    return (this.$route.params as any).id
  }

  private get chartType() {
    return parseChartType(this.currentGridItem?.chartType || '')
  }

  async initSetting() {
    if (this.currentGridItem) {
      this.formItems = await this.getFormItems()
      this.initFormData()
      this.loadingCount -= 1
    }
  }

  /** 获取表单配置选项 */
  getFormItems = async () => {
    const formItems = ChartProtoConfig[this.chartType] || []
    // if (this.chartType === 'filterForm') {
    //   /** 深度拷贝，防止连带污染 */
    //   const filterFormItems = await this.getFilterFormConfig(
    //     cloneDeep(formItems)
    //   )
    //   return filterFormItems
    // }
    return cloneDeep(formItems)
  }

  /**
   * 初始化数据
   */
  initFormData() {
    if (
      KGraphStore.currentGridItem &&
      KGraphStore.currentGridItem.chartOptions
    ) {
      this.formData = {
        ...this.currentGridItem?.chartOptions,
      }
    }
  }

  /**
   * 重置参数
   */
  private onFormSettingReset({ type, widgetInfo }: any) {
    if (type === 'fetch') {
      this.formData = {
        ...this.formData,
        ...widgetInfo,
        labelKey: '',
        valueKey: '',
        groups: undefined,
        // labelIsShow: false,
      }
      if (this.currentGridItem) {
        // @ts-ignore
        this.$set(this.currentGridItem.dataQuery, 'data', {
          ...this.currentGridItem?.dataQuery?.data,
          ...widgetInfo,
          widgetJson: {},
        })
        this.$set(this.currentGridItem.chartOptions, 'value', [])
      }
    }
  }

  private onFormSettingChange(formSetting: any) {
    console.log(formSetting)
    /** 如果回调状态 */
    // if (this.chartType === 'table') {
    //   this.onChangeTableConfig(formSetting)
    //   return
    // }
    if (GRAPH_ARRAY.includes(this.chartType)) {
      // graph 处理
      // @ts-ignore
      this.parseGraphSettingChange(formSetting)
      return
    }
    const { type, data, widgetInfo } = formSetting
    const isGeo = this.chartType === 'geographicMap'
    if (type === 'property') {
      if (Array.isArray(this.formData.size)) {
        this.formData.size = this.currentGridItem?.chartOptions.size
        data.size = this.currentGridItem?.chartOptions.size
      }
      // 属性配置变化
      if (!isGeo) {
        this.formData = parseSettingToChartOption({
          ...this.formData,
          ...data,
        })
      } else {
        this.formData = {
          ...this.formData,
          ...data,
        }
      }

      // const index = this.getCurrentIndex()
      let newChartOptions: any = this.formData
      if (isGeo) {
        newChartOptions = KGraphStore.currentGridItem?.chartOptions
        newChartOptions.glyphConfig = {
          ...newChartOptions.glyphConfig,
          ...data,
        }
      }
      if (
        ['barChart', 'lineChart', 'stackBarChart', 'groupBarChart'].includes(
          this.chartType
        )
      ) {
        this.formData.yAxisIsShow = true
        this.formData.xAxisIsShow = true
        this.formData.axisGridIsShow = true
      }
      if (this.chartType === 'dualAxesChart') {
        if (data.dualaxesType === 'line') {
          newChartOptions.geometryOptions = [
            { geometry: 'line' },
            { geometry: 'line' },
          ]
        } else {
          delete newChartOptions?.geometryOptions
        }
      }
      if (this.chartType === 'wordCloud') {
        newChartOptions.imageMask = newChartOptions?.imageMaskObj?.url
        newChartOptions.wordField = newChartOptions?.labelKey
        newChartOptions.weightField = newChartOptions?.valueKey
      }
      KGraphStore.updateWidget({
        gridItem: {
          ...KGraphStore.currentGridItem,
          chartOptions: newChartOptions,
        },
      })

      // }
    } else if (type === 'fetch') {
      // 获取数据配置变化
      const { widgetJson, id, type: dataType } = widgetInfo
      const { keys, values } = widgetJson.config
      this.formData = {
        ...this.formData,
        value: data,
        labelKey: keys[0].col,
        valueKey: values[0].col,
        dataId: id,
        dataType,
      }
      KGraphStore.gridItemBindData({
        entityId: KGraphStore.currentGridItem.entityId,
        query: {
          data: {
            id,
            type: dataType,
            widgetJson,
          },
        },
        data,
        // columns: this.fields,
        formData: cloneDeep(this.formData),
      })
    } else if (type === 'interact') {
      // const index = this.getCurrentIndex()
      KGraphStore.updateWidget({
        gridItem: {
          ...KGraphStore.currentGridItem,
          interactActive: {
            turnOn: data,
          },
        },
        // index,
      })
    }
  }
}
</script>

<style lang="less" scoped>
.position-right {
  right: 300px;
}

.config-container {
  background: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.18);
  height: 100%;
  position: absolute;
  top: 1px;
  width: 300px;
  z-index: 1001;

  .header {
    align-items: center;
    // cursor: grab;
    display: flex;
    justify-content: space-between;
    margin: 9px 12px;

    .func-icon {
      align-items: center;
      border-radius: 2px;
      color: rgb(93, 99, 126);
      cursor: pointer;
      display: flex;
      font-size: 16px;
      padding: 4px;
      position: relative;
      user-select: none;
    }
  }

  .config-body {
    height: calc(100% - 24px);
    overflow-y: scroll;
  }
}
</style>
